<!DOCTYPE html>
<!--suppress ALL -->
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>科学计算器</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    <script src="https://mirrors.sustech.edu.cn/cdnjs/ajax/libs/mathjax/2.7.9/MathJax.js?config=TeX-AMS_HTML"></script>
</head>
<body>
    <div class="container">
        <h1>科学计算器</h1>
        <div id="latexDisplay" class="latex-display">输入数学表达式...</div>
        <button onclick="calculate()">计算</button>
        <button onclick="approximate()">近似计算</button>

        <div id="result"></div>

        <h2>虚拟键盘</h2>
        <table class="keyboard">
            <tr>
                <td><button onclick="appendToExpression('7')">7</button></td>
                <td><button onclick="appendToExpression('8')">8</button></td>
                <td><button onclick="appendToExpression('9')">9</button></td>
                <td><button onclick="appendToExpression('/')">/</button></td>
            </tr>
            <tr>
                <td><button onclick="appendToExpression('4')">4</button></td>
                <td><button onclick="appendToExpression('5')">5</button></td>
                <td><button onclick="appendToExpression('6')">6</button></td>
                <td><button onclick="appendToExpression('*')">*</button></td>
            </tr>
            <tr>
                <td><button onclick="appendToExpression('1')">1</button></td>
                <td><button onclick="appendToExpression('2')">2</button></td>
                <td><button onclick="appendToExpression('3')">3</button></td>
                <td><button onclick="appendToExpression('-')">-</button></td>
            </tr>
            <tr>
                <td><button onclick="appendToExpression('0')">0</button></td>
                <td><button onclick="appendToExpression('.')">.</button></td>
                <td><button onclick="appendToExpression('(')">(</button></td>
                <td><button onclick="appendToExpression(')')">)</button></td>
            </tr>
            <tr>
                <td><button onclick="inputAngle('sin')">sin</button></td>
                <td><button onclick="inputAngle('cos')">cos</button></td>
                <td><button onclick="inputAngle('tan')">tan</button></td>
                <td><button onclick="appendToExpression('+')">+</button></td>
            </tr>
            <tr>
                <td><button onclick="appendToExpression('!')">!</button></td>
            </tr>
            <tr>
                <td colspan="1"><button onclick="deleteLastCharacter()">删除</button></td>
                <td><button onclick="appendToExpression('pi')">π</button></td>
                <td><button onclick="inputPower()">^</button></td>
                <td colspan="1"><button onclick="clearExpression()">清除</button></td>
            </tr>
        </table>
    </div>

    <script>
        let expression = '';

        function deleteLastCharacter() {
            if (expression.length > 0) {
                expression = expression.slice(0, -1);
                updateLatexDisplay();
            }
        }

        function appendToExpression(value) {
            expression += value;
            updateLatexDisplay();
        }

        function clearExpression() {
            expression = '';
            updateLatexDisplay();
        }

        function updateLatexDisplay() {
            const latexExpression = convertToLatex(expression);
            const latexDisplay = document.getElementById('latexDisplay');
            latexDisplay.innerHTML = `\\(${latexExpression}\\)`;
            MathJax.Hub.Queue(["Typeset", MathJax.Hub, latexDisplay]);
        }

        function convertToLatex(expr) {
            return expr
                .replace(/\\/g, '\\backslash')
                .replace(/\+/g, '+')
                .replace(/-/g, '-')
                .replace(/\*/g, '\\times')
                .replace(/\//g, '\\div')
                .replace(/sin/g, '\\sin')
                .replace(/cos/g, '\\cos')
                .replace(/tan/g, '\\tan')
                .replace(/(\d+(\.\d+)?)\s*\^(\s*(\d+(\.\d+)?|(sin|cos|tan|pi|!)))/g, '{$1} ^ {$4}')
                .replace(/(sin|cos|tan|pi|!)\s*\^(\s*(\d+(\.\d+)?|(sin|cos|tan|pi|!)))/g, '\\\\${2} ^ {$4}')
                .replace(/!/g, '\!')
                .replace(/_/g, '_')
                .replace(/pi/g, '\\pi');
        }

        function inputAngle(func) {
            let angle = prompt("请输入角度（度 分 秒，使用空格分隔）或小数：");
            if (angle) {
                const angleInRadians = convertToSymbolicRadians(angle);
                appendToExpression(`${func}(${angleInRadians})`);
            }
        }

        function convertToSymbolicRadians(angle) {
            const parts = angle.trim().split(' ');
            let radiansExpression = '';

            if (parts.length === 3) {
                // 处理度 分 秒
                const degrees = parts[0];
                const minutes = parts[1];
                const seconds = parts[2];
                radiansExpression = `(${degrees} + ${minutes} / 60 + ${seconds} / 3600) * pi / 180`;

            } else if (parts.length === 2) {
                // 处理度 分
                const degrees = parts[0];
                const minutes = parts[1];
                radiansExpression = `(${degrees} + ${minutes} / 60) * pi / 180`;
            } else {
                // 处理小数
                radiansExpression = `(${angle}) * pi / 180`;
            }
            return radiansExpression;
        }

        function calculate() {
            fetch('/calculate', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    'expression': expression
                })
            })
            .then(response => response.json())
            .then(data => {
                let resultDiv = document.getElementById('result');
                if (data.error) {
                    resultDiv.innerHTML = `<p style="color: red;">错误: ${data.error}</p>`;
                } else {
                    resultDiv.innerHTML = `<p>结果: ${data.result}</p>`;
                    resultDiv.innerHTML += `<p>Latex: \\(${data.latex}\\)</p>`;
                    MathJax.Hub.Queue(["Typeset", MathJax.Hub, resultDiv]);
                }
            });
        }
        function approximate() {
            fetch('/approximate', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    'expression': expression
                })
            })
            .then(response => response.json())
            .then(data => {
                let resultDiv = document.getElementById('result');
                if (data.error) {
                    resultDiv.innerHTML = `<p style="color: red;">错误: ${data.error}</p>`;
                } else {
                    resultDiv.innerHTML = `<p>近似结果: ${data.result}</p>`;
                }
            });
        }
        function inputPower() {
            let base = prompt("请输入底数：");
            let exponent = prompt("请输入指数：");
            if (base && exponent) {
                appendToExpression(`${base} ^ ${exponent}`);
            }
        }
    </script>
</body>
</html>
